package com.zeratul.common.satoken.config;

import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.same.SaSameUtil;
import com.zeratul.common.core.result.R;
import com.zeratul.common.satoken.advice.SaTokenExceptionHandler;
import com.zeratul.common.satoken.codes.AuthResultCodes;
import com.zeratul.common.satoken.inter.SaDelegateInterceptor;
import com.zeratul.common.satoken.inter.SaTokenLogInterceptor;
import com.zeratul.web.interceptor.base.BaseHandlerInterceptor;
import jakarta.annotation.Priority;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;

/**
 * 基于web模式的相关配
 */
@AutoConfiguration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class ZeratulSaTokenWebConfiguration {

    /**
     * 加载异常处理器， @Priority(1)设置优先级比默认异常处理器优先，避免被异常被全局异常处理器处理
     * @return
     */
    @Bean
    @Priority(1)
    public SaTokenExceptionHandler saTokenExceptionHandler(){
        return new SaTokenExceptionHandler();
    }

    /**
     * 鉴权注解拦截器
     */
    @Bean
    public BaseHandlerInterceptor saAnnotation() {
        return new SaDelegateInterceptor();
    }

    /**
     * SaToken日志数据拦截器
     */
    @Bean
    public BaseHandlerInterceptor saTokenLog() {
        return new SaTokenLogInterceptor();
    }

    /**
     * SameToken全局过滤器
     * @return
     */
    @Bean
    @ConditionalOnProperty(prefix = "sa-token", name = "check-same-token", havingValue = "true")
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
                .addInclude("/**")
                .addExclude("/favicon.ico")
                .setAuth(obj -> {
                    // 校验 Same-Token 身份凭证
                    SaSameUtil.checkCurrentRequestToken();
                })
                .setError(e -> R.fail(AuthResultCodes.FORBIDDEN_INTERNAL_SERVICE, e.getMessage()));
    }
}
